package com.youkeyi.ddy.cloud.application.system.login.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.youkeyi.ddy.cloud.application.system.login.service.WeChatOfficialService;
import com.youkeyi.ddy.cloud.common.response.ResponseObjectContent;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author zty_Love
 * @date 2024/06/06.
 * @time 14:07
 **/
@Slf4j
@Service
public class WeChatOfficialServiceImpl implements WeChatOfficialService {

    private static final String appId = "wx5589a0e69a84dbef";
    private static final String appSecret = "844c5fd085b5fb35641405a790bf94f7";

    @Override
    public ResponseObjectContent generateWeChatConfig(String url) {
        ResponseObjectContent<Map<String,String>> rtn=new ResponseObjectContent<>();
        Map<String, String> result = new HashMap<>();
        // 实现生成微信配置的逻辑，
        try {
            String jsapiTicket = getJsapiTicket(getAccessToken());
            String nonceStr = createNonceStr();
            String timestamp = createTimestamp();
            String signature = generateSignature(jsapiTicket, nonceStr, timestamp, url);

            result.put("appId", appId);
            result.put("timestamp", timestamp);
            result.put("nonceStr", nonceStr);
            result.put("signature", signature);
        } catch (IOException | NoSuchAlgorithmException e) {
            // Handle exception
            log.error("generateWeChatConfig error："+e.getMessage());
            rtn.setErrorMessage("generateWeChatConfig error："+e.getMessage());
            return rtn;
        }
        rtn.setData(result);
        rtn.setSuccess(true);
        return rtn;
    }


    private String getAccessToken() throws IOException {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
                "&appid=" + appId +
                "&secret=" + appSecret;
        return executeHttpGet(url).get("access_token");
    }

    private String getJsapiTicket(String accessToken) throws IOException {
        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket" +
                "?access_token=" + accessToken +
                "&type=jsapi";
        return executeHttpGet(url).get("ticket");
    }

    private Map<String, String> executeHttpGet(String url) throws IOException {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url);
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                return new ObjectMapper().readValue(response.getEntity().getContent(), Map.class);
            }
        }
    }

    private String createNonceStr() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    private String createTimestamp() {
        return String.valueOf(System.currentTimeMillis() / 1000);
    }

    private String generateSignature(String jsapiTicket, String nonceStr, String timestamp, String url)
            throws NoSuchAlgorithmException {
        String str = "jsapi_ticket=" + jsapiTicket +
                "&noncestr=" + nonceStr +
                "&timestamp=" + timestamp +
                "&url=" + url;
        MessageDigest crypt = MessageDigest.getInstance("SHA-1");
        crypt.reset();
        crypt.update(str.getBytes());
        byte[] digest = crypt.digest();
        Formatter formatter = new Formatter();
        for (byte b : digest) {
            formatter.format("%02x", b);
        }
        String signature = formatter.toString();
        formatter.close();
        return signature;
    }
}
